#include "main.h"
#include "conf.h"
#include "stm32g0xx_hal.h"
#include "stdio.h"
#include "rtc.h"
#include "time.h"

uint8_t TYPE = BAT_TYPE;
uint32_t poweronReason = 0;

void PrintResetReason(void) {
    // ?????????
    poweronReason = RCC->CSR;
	
    // ??????
    printf("Reset Reason: %d", poweronReason);

	  //if (resetFlags & RCC_CSR_FWRSTF) {
    //    printf("[Firewall] ");
    //}
		if (poweronReason & RCC_CSR_PWRRSTF) {
        printf("RCC_CSR_PWRRSTF ");
    }
    if (poweronReason & RCC_CSR_RMVF) {
        printf("[RCC_CSR_FWRSTF] ");
    }
    if (poweronReason & RCC_CSR_OBLRSTF) {
        printf("[Option Byte Loader] ");
    }
		if (poweronReason & RCC_CSR_PINRSTF) {
        printf("[NRST Pin] ");
    }
		//if (poweronReason & RCC_CSR_PORRSTF) {
    //    printf("[Power-On] ");
    //}
    if (poweronReason & RCC_CSR_SFTRSTF) {
        printf("[Software] ");
    }
    if (poweronReason & RCC_CSR_IWDGRSTF) {
        printf("[Independent Watchdog] ");
    }
    if (poweronReason & RCC_CSR_WWDGRSTF) {
        printf("[Window Watchdog] ");
    }
    if (poweronReason & RCC_CSR_LPWRRSTF) {
        printf("[Low-Power] ");
    }

    printf("\r\n");

    // ????????(? 1 ??)
    SET_BIT(RCC->CSR, RCC_CSR_RMVF);
}

uint8_t TimerWakeUPReboot(void)
{	 
	 return poweronReason == 0;
}

void EnableBLE(void)
{
	HAL_GPIO_WritePin(BLE_CHARGE_GPIO_Port, BLE_CHARGE_Pin, GPIO_PIN_SET);
	HAL_Delay(10);
}

void DisableBLE(void)
{
	HAL_GPIO_WritePin(BLE_CHARGE_GPIO_Port, BLE_CHARGE_Pin, GPIO_PIN_RESET);
}

void EnableTHandNTC(void)
{
	HAL_GPIO_WritePin(NTC_CHARGE_GPIO_Port, NTC_CHARGE_Pin, GPIO_PIN_SET);
}

void DisableTHandNTC(void)
{
	HAL_GPIO_WritePin(NTC_CHARGE_GPIO_Port, NTC_CHARGE_Pin, GPIO_PIN_RESET);
}

void EnterSTANDBYMode(void)
{
	HAL_PWR_EnterSTANDBYMode();
}

void EnterSTOPandWait(uint32_t seconds)
{
		HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, seconds, RTC_WAKEUPCLOCK_CK_SPRE_16BITS);
		EnterSTANDBYMode();
}

//RTC https://blog.csdn.net/qq_35002379/article/details/126940291
void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
{
	//static int counter = 0;
	//if (counter %2 == 0) {
		printf("HAL_RTCEx_WakeUpTimerEventCallback...\r\n");
	//}
	//counter = counter + 1;
}

static uint32_t xorshift_state = 0;

void srand_xorshift(uint32_t seed) {
    xorshift_state = seed ? seed : 0xACE1u;
}

uint32_t rand_xorshift(void) {
    xorshift_state ^= xorshift_state << 13;
    xorshift_state ^= xorshift_state >> 17;
    xorshift_state ^= xorshift_state << 5;
    return xorshift_state;
}

// ???????
uint32_t generate_seed(void) {
    uint32_t seed = HAL_GetTick();             // ????
    seed ^= (uint32_t)__get_IPSR();            // ????
    seed ^= (uint32_t)&seed;                   // ????
    return seed ? seed : 1;
}

// ???????
uint32_t rand_range(uint32_t min, uint32_t max) {
    uint32_t range = max - min + 1;
    return min + (rand_xorshift() % range);
}

